package test.java.clone;

import lombok.Data;
import lombok.ToString;
import test.java.clone.bean.Dept;
import test.java.clone.bean.Emp;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZCW
 * @createTime 2018/1/16
 * @lastUpdateTime 2018/1/16 ZCW
 */
@ToString
public class Clone {
    Emp emp;
    List<Emp> emps;
    Dept dept;

    {
        emp = new Emp("张一");

        emps = new ArrayList<Emp>();
        emps.add(emp);

        dept = new Dept("开发", emps);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CloneNotSupportedException, IOException {

        Clone clone = (Clone) Class.forName("test.java.clone.Clone").newInstance();
        System.out.println(clone);

//        clone.simpleClone();
        clone.fullCloneBySerializable();

        System.out.println(clone);

    }

    public void simpleClone() throws CloneNotSupportedException {
        // 只会克隆栈中的数据数据（基础数据类型 应用数据类型地址）
        Dept dept1 = (Dept) dept.clone();
        // 修改基础数据类型
        dept1.setName("测试");
        // 修改应用数据类型
        dept1.getEmps().get(0).setName("李四");
    }

    public void fullClone() {

    }

    public void fullCloneBySerializable() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(dept);
        objectOutputStream.writeObject(new Emp("李四"));

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        System.out.println(objectInputStream.readObject());
    }
}
